//
//  XPComposeController.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/19.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit
import SVProgressHUD

class XPComposeController: UIViewController {
    // MARK: - 懒加载控件
    /// 完成按钮
    private lazy var doneButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(XPComposeController.sendWeibo), forControlEvents: .TouchUpInside)
        button.setTitle("完成", forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.frame.size = CGSizeMake(45, 30)
        return button
    }()
    
    /// titleView
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        let username = (XPUserAccountViewModel.defaultUserAccount.userAccount?.name)!
        let title = "发微博\n\(username)"
        let attributedText = NSMutableAttributedString(string: title)
        let attr = [NSForegroundColorAttributeName: UIColor.darkGrayColor(),
                    NSFontAttributeName: UIFont.systemFontOfSize(12)
        ]
        let range = (title as NSString).rangeOfString(username)
        attributedText.addAttributes(attr, range: range)
        titleLabel.attributedText = attributedText
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .Center
        titleLabel.sizeToFit()
        return titleLabel
    }()
    
    /// 发送微博的文本框
    private lazy var textView: XPTextView = {
        let textView = XPTextView()
        textView.alwaysBounceVertical = true
        textView.placeHolder = "分享新鲜事……"
        textView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        return textView
    }()

    /// stackView
    private lazy var stackView: XPStackView = XPStackView(frame: CGRectZero)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        setupUI()
    }
    
    /// imagePicker
    private lazy var imagePicker: UIImagePickerController = UIImagePickerController()
    
    /// displayView
    private lazy var imageDisplayView: XPPictureDisplayView = XPPictureDisplayView()
    
    /// EmojiKeyBoard
    private lazy var emojiKeyboard: XPEmojiKeyboardView = {
        let emojikeyboard = XPEmojiKeyboardView()
        emojikeyboard.size = CGSize(width: screenWidth, height: 258)
        return emojikeyboard
    }()
    
    func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 16, target: self, action: #selector(XPComposeController.cancelButtonClicked))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: doneButton)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleLabel
    }
    
    func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        view.addSubview(textView)
        view.addSubview(stackView)
        textView.addSubview(imageDisplayView)
        
        textView.delegate = self
        imagePicker.delegate = self
        
        stackView.seletedButtonClosure = {[weak self] (buttonType: XPStackViewButtonType) -> Void in
            
            switch buttonType {
            case .Picture:
                self?.presentViewController(self!.imagePicker, animated: true, completion: nil)
                
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                print("Emoticon")
                self?.selectEmoticonButton()
                
            case .Add:
                print("Add")
            }
            
        }
        
        imageDisplayView.didSelectedAddImageItem = { [weak self] in
            self?.presentViewController(self!.imagePicker, animated: true, completion: nil)
        }
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view); make.leading.equalTo(view)
            make.trailing.equalTo(view); make.bottom.equalTo(view)
        }
        
        stackView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view); make.trailing.equalTo(view)
            make.height.equalTo(44); make.bottom.equalTo(view)
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XPComposeController.keyBoardFrameChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XPComposeController.emoticonButtonClicked(_:)), name: XPEmojiDisplayCellNotificationName, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK: - 点击事件
extension XPComposeController {
    /// 取消
    @objc private func cancelButtonClicked() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 完成
    @objc private func sendWeibo() {
        SVProgressHUD.show()
        let accessToken = XPUserAccountViewModel.defaultUserAccount.accessToken!
        let statuses = textView.text ?? ""
        
        if imageDisplayView.hidden {
            XPNetworkTool.sharedTools.statusesUpdate(accessToken, status: statuses) { (response, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.refreshHomePage()
            }
        } else {
            guard let uploadImages: [UIImage] = imageDisplayView.images else {
                return
            }
            
            XPNetworkTool.sharedTools.statusesUpload(accessToken, status: statuses, images: uploadImages, resultClosure: { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("上传失败!")
                    return
                }
                self.refreshHomePage()
            })
        }
    }
    
    func refreshHomePage() {
        self.view.endEditing(true)
        self.dismissViewControllerAnimated(true, completion: { () -> Void in
            SVProgressHUD.dismiss()
        })
    }
    
    @objc private func keyBoardFrameChange(note: NSNotification) {
//        UIKeyboardAnimationDurationUserInfoKey = "0.25";
//        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        
        let moveY = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().origin.y - view.height
        let durationTime = (note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        UIView.animateWithDuration(durationTime, animations: { () -> Void in
            self.stackView.transform = CGAffineTransformMakeTranslation(0, moveY)
        })
    }
    
    @objc private func emoticonButtonClicked(note: NSNotification) {
        let emoticon: XPEmoticon = note.object as! XPEmoticon
        
        if emoticon.type == "0" {
            textView.text = "\(textView.text ?? "")\(emoticon.chs!)"
        }else {
            textView.text = "\(textView.text ?? "")\(emoticon.code!.emoji())"
        }
        
    }
    
    private func selectEmoticonButton() {
        if textView.inputView == nil {
            textView.inputView = emojiKeyboard
        } else {
            textView.inputView = nil
        }
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }
}

// MARK: - UITextView代理方法
extension XPComposeController: UITextViewDelegate, UIScrollViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        picker.dismissViewControllerAnimated(true) {[weak self] () -> Void in
            self?.imageDisplayView.images.append(UIImage.compressImage(image, targetWidth: 500))
        }
    }
}
